/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao.Funcionario;

import Controle.Controlador;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Andre Luiz
 */
public class GerenciarClientes extends javax.swing.JFrame {
    ArrayList<ArrayList<String>> clientes;
    DefaultTableModel modelo;
    TableRowSorter sorter;

    /**
     * Creates new form GerenciarClientes
     */
    public GerenciarClientes() {
        initComponents();
        modelo = (DefaultTableModel) jtabela.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1. getViewport().setBackground(Color.WHITE);
        jtabela.getColumnModel().getColumn(0).setMinWidth(0);
        jtabela.getColumnModel().getColumn(0).setMaxWidth(0);
        jtabela.getColumnModel().getColumn(1).setPreferredWidth(140);
        jtabela.getColumnModel().getColumn(7).setPreferredWidth(110);
        jtabela.getColumnModel().getColumn(8).setPreferredWidth(25);
        clientes=imprimeDadosTabelas(carregarDadosBD());
    }
    
    /**
     * Carrega todos os sabores do banco de dados
     * @return Retorna uma lista de Sabores 
     */
    private ArrayList<ArrayList<String>> carregarDadosBD(){
        return Controlador.carregarDadosBD_Clientes();
    }
    
    private ArrayList<ArrayList<String>> imprimeDadosTabelas(ArrayList<ArrayList<String>> clientes) {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela = 0;
        jtabela.setRowSorter(null); // desabilita o filtro
        
        for (int i = 0; i < clientes.size(); i++) {
            try{
                if (jtabela.getRowCount() <= linhaTabela) {
                    modelo.addRow(new String[]{"", ""});
                }
                jtabela.setValueAt(clientes.get(i).get(0), linhaTabela, 0);
                jtabela.setValueAt(clientes.get(i).get(1), linhaTabela, 1);
                jtabela.setValueAt(clientes.get(i).get(2), linhaTabela, 2);
                jtabela.setValueAt(clientes.get(i).get(3), linhaTabela, 3);
                jtabela.setValueAt(clientes.get(i).get(5), linhaTabela, 4);
                jtabela.setValueAt(clientes.get(i).get(6), linhaTabela, 5);
                jtabela.setValueAt(clientes.get(i).get(8), linhaTabela, 6);
                jtabela.setValueAt(clientes.get(i).get(9), linhaTabela, 7);
                jtabela.setValueAt(clientes.get(i).get(10), linhaTabela, 8);
                jtabela.setValueAt(clientes.get(i).get(11), linhaTabela, 9);
            }catch(Exception ex){
                System.out.println("Erro ao imprimir os dados na tabela\n"+ex.getMessage());
            }

            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        //reativa o filtro
        jFiltroKeyReleased(null);
        return clientes;
    }
    
    public void atualizaTabela(){
        imprimeDadosTabelas(carregarDadosBD());
    }
    
    public void removeLinhasInutilizadas(int linhaTabela){
        for (int i = linhaTabela; i < jtabela.getRowCount(); i++) {
            modelo.removeRow(i);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtabela = new javax.swing.JTable();
        jEditar = new javax.swing.JButton();
        jbInserirCliente = new javax.swing.JButton();
        jFiltro = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jbRemover = new javax.swing.JButton();
        jcfiltroColuna = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Clientes");

        jtabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Nome", "RG", "Data Nasc", "Fone 1", "Fone 2", "Bairro", "Rua", "Num", "Complemento"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jtabela);

        jEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/editarCliente.png"))); // NOI18N
        jEditar.setToolTipText("Editar Cliente");
        jEditar.setMinimumSize(new java.awt.Dimension(64, 64));
        jEditar.setPreferredSize(new java.awt.Dimension(64, 64));
        jEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jEditarActionPerformed(evt);
            }
        });

        jbInserirCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/addCliente.png"))); // NOI18N
        jbInserirCliente.setToolTipText("Cadastrar Cliente");
        jbInserirCliente.setMinimumSize(new java.awt.Dimension(64, 64));
        jbInserirCliente.setPreferredSize(new java.awt.Dimension(70, 64));
        jbInserirCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbInserirClienteActionPerformed(evt);
            }
        });

        jFiltro.setToolTipText("Filtra Dados");
        jFiltro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jFiltroKeyReleased(evt);
            }
        });

        jLabel1.setText("Filtro:");

        jbRemover.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/delCliente.png"))); // NOI18N
        jbRemover.setToolTipText("Remover Cliente");
        jbRemover.setMinimumSize(new java.awt.Dimension(64, 64));
        jbRemover.setPreferredSize(new java.awt.Dimension(64, 64));
        jbRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbRemoverActionPerformed(evt);
            }
        });

        jcfiltroColuna.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todas as Colunas", "Nome", "RG", "Fone 1", "Fone 2", "Bairro", "Rua", "Num", "Complemento" }));

        jLabel2.setText("Coluna:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFiltro, javax.swing.GroupLayout.DEFAULT_SIZE, 862, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jcfiltroColuna, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jEditar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbInserirCliente, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jbRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1)
                            .addComponent(jcfiltroColuna, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(89, 89, 89)
                        .addComponent(jbInserirCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jbRemover, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-1255)/2, (screenSize.height-546)/2, 1255, 546);
    }// </editor-fold>//GEN-END:initComponents

    private void jFiltroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jFiltroKeyReleased
        // Filtro:
        try{
            if(jcfiltroColuna.getSelectedIndex()==0){
            sorter.setRowFilter(RowFilter.regexFilter(jFiltro.getText().toUpperCase()));
            jtabela.setRowSorter(sorter);
        }
        else{
            sorter.setRowFilter(RowFilter.regexFilter(jFiltro.getText().toUpperCase(),jcfiltroColuna.getSelectedIndex()));
            jtabela.setRowSorter(sorter);
        }
        }catch(Exception ex){
            System.out.println("Erro ao Fitrar os dados da Tabela!");
        }
        
        
    }//GEN-LAST:event_jFiltroKeyReleased

    private void jbInserirClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbInserirClienteActionPerformed
        // Inserir Cliente:
        new InserirAlterarCliente(this).setVisible(true);
    }//GEN-LAST:event_jbInserirClienteActionPerformed

    private void jEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jEditarActionPerformed
        // Editar Cliente:
        try {
            int linha = jtabela.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt(jtabela.getValueAt(linha, 0).toString().replace(" ", ""));
                InserirAlterarCliente inserir = new InserirAlterarCliente(this, codigo);
                inserir.setVisible(true);
                
            } else {
                throw new Exception("Selecione a linha do Cliente desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jEditarActionPerformed

    private void jbRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbRemoverActionPerformed
        // Remover Cliente
       try {
            int linha = jtabela.getSelectedRow();
            if (linha != -1) {
                int codigo = Integer.parseInt(jtabela.getValueAt(linha, 0).toString());
                int aux = JOptionPane.showConfirmDialog(this, "Deseja realmente remover o Cliente Selecionado? ", "Remover Cliente", 1,3);
                if(aux==0){
                    Controlador.remover_Cliente(codigo);
                    atualizaTabela();
                }
            } else {
                throw new Exception("Selecione a linha do Cliente desejado");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jbRemoverActionPerformed

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jEditar;
    private javax.swing.JTextField jFiltro;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbInserirCliente;
    private javax.swing.JButton jbRemover;
    private javax.swing.JComboBox jcfiltroColuna;
    private javax.swing.JTable jtabela;
    // End of variables declaration//GEN-END:variables
}
